package com.skplanet.rade.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.skplanet.rade.dao.TagDAO;
import com.skplanet.rade.domain.StoryTag;
import com.skplanet.rade.domain.Tag;
import com.skplanet.rade.domain.UserTag;

@Service(value = "tagService")
@Transactional
public class TagService {

	@Autowired
	private TagDAO tagDAO;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Transactional
	public void update(Tag tag) {
		tagDAO.update(tag);
	}

	@Transactional
	public void addTag(Tag tag) {
		tagDAO.save(tag);
	}

	@Transactional
	public Tag addUserTag(UserTag userTag) {
		Tag newTag = tagDAO.findUniqByObject("keyword", userTag.getKeyword());
		if (newTag == null) {
			newTag = new Tag();
			newTag.setKeyword(userTag.getKeyword());
			// tagDAO.save(newTag);
		}
		newTag.adduCount();
		newTag.addUserTag(userTag);

		// tagDAO.update(newTag);
		return newTag;
	}

	@Transactional(readOnly = true)
	public Tag select(String tagId) {
		Tag tag = tagDAO.select(tagId);
		return tag;
	}

	@Transactional(readOnly = true)
	public String getTagIdFromKeyword(String Keyword) {
		return (String) tagDAO.findColumnByObject("tid", "keyword", Keyword);
	}

	@Transactional(readOnly = true)
	public Tag getTagFromKeyword(String keyword) {
		return (Tag) tagDAO.findUniqByObject("keyword", keyword);
	}

	@Transactional(readOnly = true)
	public List<Tag> getAllTag() {
		return tagDAO.getAll();
	}

	@Transactional(readOnly = true)
	public boolean keywordExists(String keyword) {
		return tagDAO.rowExists("keyword", keyword);
	}

	@Transactional
	public void removeStoryTag(Tag tag, long stid) {
		// Tag tag = tagDAO.findUniqByObject("tid", tid);

		for (int i = 0; i < tag.getStoryTags().size(); i++) {
			if (tag.getStoryTags().get(i).getStid() == stid) {
				tag.getStoryTags().remove(i);

				update(tag);
				return;
			}
		}
	}

	@Transactional
	public Tag addStoryTag(StoryTag storyTag) {
		Tag newTag = tagDAO.findUniqByObject("keyword", storyTag.getKeyword());
		if (newTag == null) {
			newTag = new Tag();
			newTag.setKeyword(storyTag.getKeyword());
		}
		newTag.addsCount();
		newTag.addStoryTag(storyTag);

		addTag(newTag);

		return newTag;
	}

	@Transactional
	public List<Tag> getNTagList(int n) {
		List<Tag> tagList = new ArrayList<Tag>();
		List<Tag> topNTagList = new ArrayList<Tag>();

		tagList = tagDAO.getAll();

		Collections.sort(tagList, Tag.getTagcomparator());

		for (int i = 0; i < n && i < tagList.size(); i++) {
			topNTagList.add(tagList.get(i));
		}

		return topNTagList;
	}
}
